
var File1 = typeof File !== 'undefined' ? File : require('fs').File;
var Directory1 = typeof Directory !== 'undefined' ? Directory : require('fs').Directory;

var echo = function(msg) {
	system.stdout(msg + '\n');
}

var readFile = function(filename, silentFail) {
	var str = '', opened = false, f;
	try {
		f = new File1(filename);
		f.open('r');
		opened = true;
		str = f.read().toString('UTF-8');
	} catch(e) {
		if (silentFail)
			str = null;
		else
			echo('Exception reading file "' + filename + '"');
	}
	if (opened)
		f.close();
	return str;
}

exports.writeFile = function(filename, data) {
	var str = '', opened = false, f;
		try {
			f = new File1(filename);
			f.open('w');
			opened = true;
			f.write(data);
		} catch(e) {
			echo('Exception writing to file "' + filename + '"');
		}
		if (opened)
			f.close();
}

var listFiles = function(dir, extension, prefix) {
	var d = new Directory1(dir);
	var files = d.listFiles();
	var rx, pre;
	if (arguments.length > 1) rx = new RegExp('\\.' + extension + '$');
	if (arguments.length > 2) pre = new RegExp('^' + prefix + '\\.');
	for (var i = 0; i < files.length; i++)
		if (!(arguments.length < 2 || (rx.test(files[i]) && (arguments.length < 3 || pre.test(files[i]))))) {
			files.splice(i, 1);
			i--;
		}
	return files;
}

var ensurePathExists = function(filepath) {
	var folders = filepath.split('/');
	if (!folders[folders.length-1]) folders.pop();
	var now = '';
	for (var i = 0; i < folders.length; i++) {
		if (i) now += '\\'
		now += folders[i];
		var d = new Directory1(now);
		if (!d.exists())
			d.create();
	}
}

exports.copyFile = function(source, target) {
	new File1(source).copy(target);
}

exports.fileExists = function(filename) {
	return new File1(filename).exists();
}

exports.deleteFile = function(filename) {
	new File1(filename).remove();
}

exports.deleteFolder = function(folder) {
	new Directory1(folder).remove();
}

var fileModified = function(filename) {
	return new File1(filename).stat().mtime;
}

var copyFolder = function(source, target) {
	var src = new Directory1(source);
	var dest = new Directory1(target);
	if (!dest.exists()) dest.create();
	var files = src.listFiles();
	
	for (var i = 0; i < files.length; i++)
		if (copyFolder.blacklist.indexOf(files[i]) < 0)
			new File1(source + '/' + files[i]).copy(target + '/' + files[i]);
	var dirs = src.listDirectories();
	for (var i = 0; i < dirs.length; i++)
		copyFolder(source+ '/' + dirs[i], target + '/' + dirs[i]);
}
copyFolder.blacklist = [ 'Thumbs.db' ];

// skip 1st argument, which is path to current executing script
exports.args = system.args.slice(1);

exports.echo = echo;
exports.readFile = readFile;
exports.ensurePathExists = ensurePathExists;
exports.listFiles = listFiles;
exports.copyFolder = copyFolder;
exports.fileModified = fileModified;
